import { localData, WebURI } from "./const.js";
import {
  createModel,
  convertToTensor,
  trainModel,
} from "./tensorflow/index.js";

console.log(localData);

/**
 * 获取数据
 * @returns
 */
async function getData() {
  const careDataResponse = await fetch(WebURI);
  const carsData = localData || (await careDataResponse.json());
  const cleaned = carsData
    .map((car) => ({
      mpg: car.Miles_per_Gallon,
      horsepower: car.Horsepower,
    }))
    .filter((car) => car.mpg != null && car.horsepower != null);

  return cleaned;
}

function testModel(model, inputData, normalizationData) {
  const { inputMax, inputMin, labelMax, labelMin } = normalizationData;

  const [xs, preds] = tf.tidy(() => {
    // 生成新的 100 个样本
    const xs = tf.linspace(0, 1, 100);
    const preds = model.predict(xs.reshape([100, 1]));

    const unNorXs = xs.mul(inputMax.sub(inputMin)).add(inputMin);
    const unNormPreds = preds.mul(labelMax.sub(labelMin)).add(labelMin);

    return [unNorXs.dataSync(), unNormPreds.dataSync()];
  });

  const predictedPoint = Array.from(xs).map((val, i) => {
    return { x: val, y: preds[i] };
  });

  const originalPoint = inputData.map((d) => ({
    x: d.horsepower,
    y: d.mpg,
  }));

  tfvis.render.scatterplot(
    {name: "Model Predictions vs Original Data"},
    {values: [originalPoint, predictedPoint], series: ["orifinal", "predicted"]},
    {
      xLabel: "Horsepower",
      yLabel: "MPG",
      height: 300
    }
  )
}

/**
 * 运行
 */
async function run() {
  const data = await getData();
  const values = data.map((d) => ({
    x: d.horsepower,
    y: d.mpg,
  }));

  tfvis.render.scatterplot(
    { name: "马力 v 每加仑行驶的英里数" },
    { values },
    {
      xLabel: "马力",
      yLabel: "每加仑行驶的英里数",
      height: 300,
    }
  );

  const model = createModel();
  tfvis.show.modelSummary({ name: "Model Summary" }, model);

  const tensorData = convertToTensor(data);
  const { inputs, labels } = tensorData;

  await trainModel(model, inputs, labels);
  console.log("Done Traning");

  testModel(model, data, tensorData)
}

document.addEventListener("DOMContentLoaded", run);
